<template>
  <div class="permission-list-container">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <h2>权限管理</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddPermission" v-if="checkPermission('sys:permission:add')">
          <el-icon><Plus /></el-icon>
          新增权限
        </el-button>
        <el-button type="danger" @click="handleBatchDelete" v-if="checkPermission('sys:permission:delete')" :disabled="selectedRows.length === 0">
          <el-icon><Delete /></el-icon>
          批量删除
        </el-button>
        <el-button @click="handleExpandAll">
          <el-icon><Elipsis /></el-icon>
          展开全部
        </el-button>
        <el-button @click="handleCollapseAll">
          <el-icon><Fold /></el-icon>
          折叠全部
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" layout="inline" size="small" @submit.prevent>
        <el-form-item label="权限名称">
          <el-input
            v-model="searchForm.permissionName"
            placeholder="请输入权限名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input
            v-model="searchForm.permissionCode"
            placeholder="请输入权限编码"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 权限列表树 -->
    <el-card class="tree-card" shadow="hover">
      <el-tree
        ref="permissionTree"
        v-loading="loading"
        :data="permissionList"
        :props="permissionTreeProps"
        node-key="id"
        show-checkbox
        default-expand-all
        @node-click="handleNodeClick"
        @check-change="handleCheckChange"
        class="permission-tree"
      >
        <template #default="{ node, data }">
          <div class="tree-node-content">
            <span class="node-label">{{ node.label }}</span>
            <div class="node-actions" v-if="showActions(node)" @click.stop>
              <el-button
                type="primary"
                size="small"
                @click="handleEditPermission(data)"
                v-if="checkPermission('sys:permission:edit')"
              >
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="handleDeletePermission(data)"
                v-if="checkPermission('sys:permission:delete')"
                :disabled="hasChildren(data) || data.code === 'sys:manage'"
              >
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="handleAddChildPermission(data)"
                v-if="checkPermission('sys:permission:add')"
                :disabled="data.type === 2"
              >
                <el-icon><Plus /></el-icon>
                添加子权限
              </el-button>
            </div>
          </div>
        </template>
      </el-tree>
    </el-card>

    <!-- 新增/编辑权限对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="permissionFormRef"
        :model="permissionForm"
        :rules="permissionRules"
        label-width="100px"
        class="permission-form"
      >
        <el-form-item prop="parentId">
          <el-select
            v-model="permissionForm.parentId"
            placeholder="请选择父权限"
            clearable
          >
            <el-option
              v-for="item in permissionOptions"
              :key="item.id"
              :label="item.fullPath"
              :value="item.id"
              :disabled="item.id === permissionForm.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="name">
          <el-input
            v-model="permissionForm.name"
            placeholder="请输入权限名称"
            clearable
          />
        </el-form-item>
        <el-form-item prop="code">
          <el-input
            v-model="permissionForm.code"
            placeholder="请输入权限编码（如：sys:user:add）"
            clearable
            :disabled="permissionForm.code === 'sys:manage'"
          />
        </el-form-item>
        <el-form-item prop="type">
          <el-select
            v-model="permissionForm.type"
            placeholder="请选择权限类型"
            :disabled="permissionForm.code === 'sys:manage'"
          >
            <el-option label="目录" :value="0" />
            <el-option label="菜单" :value="1" />
            <el-option label="按钮" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item prop="icon" v-if="permissionForm.type !== 2">
          <el-input
            v-model="permissionForm.icon"
            placeholder="请输入图标名称（如：HomeFilled）"
            clearable
          />
        </el-form-item>
        <el-form-item prop="path" v-if="permissionForm.type !== 2">
          <el-input
            v-model="permissionForm.path"
            placeholder="请输入路由路径"
            clearable
          />
        </el-form-item>
        <el-form-item prop="component" v-if="permissionForm.type === 1">
          <el-input
            v-model="permissionForm.component"
            placeholder="请输入组件路径"
            clearable
          />
        </el-form-item>
        <el-form-item prop="sort">
          <el-input-number
            v-model="permissionForm.sort"
            :min="0"
            :max="9999"
            placeholder="排序号"
          />
        </el-form-item>
        <el-form-item prop="description">
          <el-input
            v-model="permissionForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSavePermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'PermissionList',
  setup() {
    // 树数据和加载状态
    const permissionTree = ref(null)
    const permissionList = ref([])
    const loading = ref(false)
    const selectedRows = ref([])
    
    // 搜索表单
    const searchForm = reactive({
      permissionName: '',
      permissionCode: ''
    })
    
    // 对话框状态
    const dialogVisible = ref(false)
    const dialogTitle = ref('')
    
    // 权限表单
    const permissionFormRef = ref(null)
    const permissionForm = reactive({
      id: '',
      parentId: '',
      name: '',
      code: '',
      type: 0, // 0: 目录, 1: 菜单, 2: 按钮
      icon: '',
      path: '',
      component: '',
      sort: 0,
      description: ''
    })
    
    // 权限表单验证规则
    const permissionRules = {
      name: [
        { required: true, message: '请输入权限名称', trigger: 'blur' },
        { min: 2, max: 30, message: '权限名称长度在 2 到 30 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入权限编码', trigger: 'blur' },
        { pattern: /^[a-z0-9_]+:[a-z0-9_]+(:[a-z0-9_]+)*$/, message: '权限编码格式错误（如：sys:user:add）', trigger: 'blur' }
      ],
      type: [
        { required: true, message: '请选择权限类型', trigger: 'change' }
      ]
    }
    
    // 树配置
    const permissionTreeProps = {
      label: 'name',
      children: 'children',
      isLeaf: (data) => data.type === 2
    }
    
    // 权限选项（用于选择父权限）
    const permissionOptions = computed(() => {
      const options = []
      
      const traverse = (nodes, parentPath = '') => {
        nodes.forEach(node => {
          const fullPath = parentPath ? `${parentPath} > ${node.name}` : node.name
          options.push({ id: node.id, name: node.name, fullPath: fullPath })
          
          if (node.children && node.children.length > 0) {
            traverse(node.children, fullPath)
          }
        })
      }
      
      traverse(permissionList.value)
      return options
    })
    
    // 加载权限列表
    const loadPermissionList = async () => {
      try {
        loading.value = true
        
        // 这里应该调用后端API获取真实数据
        // 由于是模拟环境，我们使用mock数据
        await new Promise(resolve => setTimeout(resolve, 500))
        
        // Mock权限数据，构建树形结构
        permissionList.value = [
          {
            id: 1,
            name: '系统管理',
            code: 'sys:manage',
            type: 0,
            icon: 'Setting',
            path: '/system',
            component: '',
            sort: 0,
            description: '系统管理模块',
            children: [
              {
                id: 2,
                name: '用户管理',
                code: 'sys:user:manage',
                type: 1,
                icon: 'User',
                path: '/system/user',
                component: 'user/UserList.vue',
                sort: 0,
                description: '用户管理模块',
                children: [
                  { id: 3, name: '查询用户', code: 'sys:user:query', type: 2, sort: 0, description: '查询用户权限' },
                  { id: 4, name: '新增用户', code: 'sys:user:add', type: 2, sort: 1, description: '新增用户权限' },
                  { id: 5, name: '编辑用户', code: 'sys:user:edit', type: 2, sort: 2, description: '编辑用户权限' },
                  { id: 6, name: '删除用户', code: 'sys:user:delete', type: 2, sort: 3, description: '删除用户权限' },
                  { id: 7, name: '分配角色', code: 'sys:user:assignRole', type: 2, sort: 4, description: '分配角色权限' }
                ]
              },
              {
                id: 8,
                name: '角色管理',
                code: 'sys:role:manage',
                type: 1,
                icon: 'Avatar',
                path: '/system/role',
                component: 'role/RoleList.vue',
                sort: 1,
                description: '角色管理模块',
                children: [
                  { id: 9, name: '查询角色', code: 'sys:role:query', type: 2, sort: 0, description: '查询角色权限' },
                  { id: 10, name: '新增角色', code: 'sys:role:add', type: 2, sort: 1, description: '新增角色权限' },
                  { id: 11, name: '编辑角色', code: 'sys:role:edit', type: 2, sort: 2, description: '编辑角色权限' },
                  { id: 12, name: '删除角色', code: 'sys:role:delete', type: 2, sort: 3, description: '删除角色权限' },
                  { id: 13, name: '分配权限', code: 'sys:role:assignPermission', type: 2, sort: 4, description: '分配权限权限' }
                ]
              },
              {
                id: 14,
                name: '权限管理',
                code: 'sys:permission:manage',
                type: 1,
                icon: 'Lock',
                path: '/system/permission',
                component: 'permission/PermissionList.vue',
                sort: 2,
                description: '权限管理模块',
                children: [
                  { id: 15, name: '查询权限', code: 'sys:permission:query', type: 2, sort: 0, description: '查询权限权限' },
                  { id: 16, name: '新增权限', code: 'sys:permission:add', type: 2, sort: 1, description: '新增权限权限' },
                  { id: 17, name: '编辑权限', code: 'sys:permission:edit', type: 2, sort: 2, description: '编辑权限权限' },
                  { id: 18, name: '删除权限', code: 'sys:permission:delete', type: 2, sort: 3, description: '删除权限权限' }
                ]
              },
              {
                id: 19,
                name: '审计日志',
                code: 'audit:manage',
                type: 1,
                icon: 'Document',
                path: '/system/audit',
                component: 'audit/AuditLog.vue',
                sort: 3,
                description: '审计日志模块',
                children: [
                  { id: 20, name: '查询日志', code: 'audit:query', type: 2, sort: 0, description: '查询日志权限' },
                  { id: 21, name: '导出日志', code: 'audit:export', type: 2, sort: 1, description: '导出日志权限' }
                ]
              }
            ]
          }
        ]
        
      } catch (error) {
        console.error('加载权限列表失败:', error)
        ElMessage.error('加载权限列表失败，请稍后重试')
      } finally {
        loading.value = false
      }
    }
    
    // 处理搜索
    const handleSearch = () => {
      loadPermissionList()
    }
    
    // 处理重置
    const handleReset = () => {
      Object.keys(searchForm).forEach(key => {
        searchForm[key] = ''
      })
      loadPermissionList()
    }
    
    // 处理展开全部
    const handleExpandAll = () => {
      permissionTree.value && permissionTree.value.expandAll()
    }
    
    // 处理折叠全部
    const handleCollapseAll = () => {
      permissionTree.value && permissionTree.value.collapseAll()
    }
    
    // 处理节点点击
    const handleNodeClick = (data, node) => {
      // 节点点击事件
    }
    
    // 处理选择变化
    const handleCheckChange = (data, checked, indeterminate) => {
      // 当选中状态变化时，更新选中的节点列表
      if (permissionTree.value) {
        selectedRows.value = permissionTree.value.getCheckedNodes()
      }
    }
    
    // 显示操作按钮
    const showActions = (node) => {
      // 只有当鼠标悬停时才显示操作按钮
      return node.isHovering
    }
    
    // 判断是否有子节点
    const hasChildren = (data) => {
      return data.children && data.children.length > 0
    }
    
    // 处理新增权限
    const handleAddPermission = () => {
      dialogTitle.value = '新增权限'
      // 重置表单
      Object.keys(permissionForm).forEach(key => {
        if (key === 'sort') {
          permissionForm[key] = 0
        } else if (key === 'type') {
          permissionForm[key] = 0
        } else {
          permissionForm[key] = ''
        }
      })
      dialogVisible.value = true
    }
    
    // 处理添加子权限
    const handleAddChildPermission = (parentData) => {
      dialogTitle.value = '添加子权限'
      // 重置表单
      Object.keys(permissionForm).forEach(key => {
        if (key === 'sort') {
          permissionForm[key] = 0
        } else if (key === 'type' && parentData.type === 0) {
          permissionForm[key] = 1
        } else if (key === 'type' && parentData.type === 1) {
          permissionForm[key] = 2
        } else if (key === 'parentId') {
          permissionForm[key] = parentData.id
        } else {
          permissionForm[key] = ''
        }
      })
      dialogVisible.value = true
    }
    
    // 处理编辑权限
    const handleEditPermission = (data) => {
      dialogTitle.value = '编辑权限'
      // 复制权限数据到表单
      Object.assign(permissionForm, { ...data })
      dialogVisible.value = true
    }
    
    // 处理保存权限
    const handleSavePermission = async () => {
      try {
        if (permissionForm.code === 'sys:manage') {
          ElMessage.warning('系统管理权限不能修改')
          return
        }
        
        await permissionFormRef.value.validate()
        
        // 这里应该调用后端API保存权限
        
        if (permissionForm.id) {
          // 编辑权限
          ElMessage.success('权限编辑成功')
        } else {
          // 新增权限
          ElMessage.success('权限新增成功')
        }
        
        // 关闭对话框并刷新列表
        dialogVisible.value = false
        loadPermissionList()
      } catch (error) {
        console.error('保存权限失败:', error)
        ElMessage.error('保存权限失败，请稍后重试')
      }
    }
    
    // 处理删除权限
    const handleDeletePermission = async (data) => {
      try {
        if (data.code === 'sys:manage') {
          ElMessage.warning('系统管理权限不能删除')
          return
        }
        
        if (hasChildren(data)) {
          ElMessage.warning('请先删除子权限')
          return
        }
        
        await ElMessageBox.confirm(
          '确定要删除该权限吗？此操作将影响所有使用该权限的角色。',
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 这里应该调用后端API删除权限
        
        ElMessage.success('权限删除成功')
        loadPermissionList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除权限失败:', error)
          ElMessage.error('删除权限失败，请稍后重试')
        }
      }
    }
    
    // 处理批量删除
    const handleBatchDelete = async () => {
      try {
        if (selectedRows.value.length === 0) {
          ElMessage.warning('请先选择要删除的权限')
          return
        }
        
        // 检查是否包含系统管理权限
        const hasSystemManage = selectedRows.value.some(row => row.code === 'sys:manage')
        if (hasSystemManage) {
          ElMessage.warning('选中的权限包含系统管理权限，无法删除')
          return
        }
        
        // 检查是否包含有子权限的节点
        const hasParentNode = selectedRows.value.some(row => hasChildren(row))
        if (hasParentNode) {
          ElMessage.warning('选中的权限包含有子权限的节点，请先删除子权限')
          return
        }
        
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedRows.value.length} 个权限吗？此操作将影响所有使用这些权限的角色。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        // 这里应该调用后端API批量删除权限
        
        ElMessage.success('权限批量删除成功')
        selectedRows.value = []
        loadPermissionList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('批量删除权限失败:', error)
          ElMessage.error('批量删除权限失败，请稍后重试')
        }
      }
    }
    
    // 处理对话框关闭
    const handleDialogClose = () => {
      if (permissionFormRef.value) {
        permissionFormRef.value.resetFields()
      }
    }
    
    // 检查权限
    const checkPermission = (permissionCode) => {
      // 从localStorage获取用户权限
      const permissions = JSON.parse(localStorage.getItem('permissions') || '[]')
      // 检查是否包含所需权限
      return permissions.includes(permissionCode)
    }
    
    onMounted(() => {
      loadPermissionList()
    })
    
    return {
      permissionTree,
      permissionList,
      loading,
      selectedRows,
      searchForm,
      dialogVisible,
      dialogTitle,
      permissionFormRef,
      permissionForm,
      permissionRules,
      permissionTreeProps,
      permissionOptions,
      handleSearch,
      handleReset,
      handleExpandAll,
      handleCollapseAll,
      handleNodeClick,
      handleCheckChange,
      showActions,
      hasChildren,
      handleAddPermission,
      handleAddChildPermission,
      handleEditPermission,
      handleSavePermission,
      handleDeletePermission,
      handleBatchDelete,
      handleDialogClose,
      checkPermission
    }
  }
}
</script>

<style scoped>
.permission-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
}

.tree-card {
  overflow-x: auto;
}

.permission-tree {
  min-height: 400px;
}

.tree-node-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.node-label {
  flex: 1;
}

.node-actions {
  display: none;
  gap: 4px;
}

.el-tree-node:hover .node-actions {
  display: flex;
}

.permission-form {
  max-height: 400px;
  overflow-y: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .header-actions {
    width: 100%;
    flex-wrap: wrap;
  }
  
  .el-form--inline .el-form-item {
    width: 100%;
    margin-bottom: 12px;
  }
  
  .el-form--inline .el-input {
    width: 100% !important;
  }
  
  .node-actions {
    display: flex;
    flex-wrap: wrap;
    margin-top: 8px;
    width: 100%;
  }
  
  .tree-node-content {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>